"""
Convert MP4 video to GIF animation.
"""

import logging
from pathlib import Path
from typing import Dict, Any
import cv2
from PIL import Image
import numpy as np
from tqdm import tqdm

def convert_mp4_to_gif(
    input_video: str,
    output_gif: str,
    frame_delay: int,
    config: Dict[str, Any]
) -> None:
    """
    Convert MP4 video to GIF animation.
    
    Args:
        input_video: Path to input MP4 file
        output_gif: Path to output GIF file
        frame_delay: Delay between frames in milliseconds
        config: Configuration dictionary
    """
    try:
        logging.info(f"Opening video file: {input_video}")
        cap = cv2.VideoCapture(input_video)
        
        if not cap.isOpened():
            raise ValueError("Could not open video file")
        
        # 获取视频信息
        frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        
        # 读取所有帧
        frames = []
        with tqdm(total=frame_count, desc="Converting frames") as pbar:
            while cap.isOpened():
                ret, frame = cap.read()
                if not ret:
                    break
                    
                # 转换 BGR 到 RGB
                rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                pil_image = Image.fromarray(rgb_frame)
                frames.append(pil_image)
                pbar.update(1)
        
        cap.release()
        
        # 保存 GIF
        logging.info(f"Saving GIF to: {output_gif}")
        frames[0].save(
            output_gif,
            save_all=True,
            append_images=frames[1:],
            duration=frame_delay,
            loop=0,
            optimize=True
        )
        
        logging.info("GIF conversion completed successfully")
        
    except Exception as e:
        logging.error(f"Error during GIF conversion: {str(e)}", exc_info=True)
        raise

def main():
    """Main function"""
    try:
        from utils import setup_logging, load_config, get_project_root
        
        # Load configuration
        config_path = get_project_root() / "config" / "settings.json"
        config = load_config(config_path)
        
        # Setup logging - pass only the logging configuration
        setup_logging(config)  # 修改这一行，删除 ['logging']
        
        logging.info("=== Starting MP4 to GIF conversion ===")
        
        # 转换视频到 GIF
        convert_mp4_to_gif(
            input_video="output/output.mp4",
            output_gif=config['output_gif'],
            frame_delay=config['frame_delay'],
            config=config
        )
        
        logging.info("=== Conversion completed successfully! ===")
        
    except Exception as e:
        logging.error(f"Conversion failed: {str(e)}", exc_info=True)
        raise

if __name__ == "__main__":
    main() 